<template>
  <div id="CompetitionLive">
    <!-- <el-button @click="changeRankInfo({matchApplyNumber:'MATCH000274-000005',num:1,time:'12:30',taskName:'nihao'})" style="position: absolute;z-index:999" type="warining" size="normal">click</el-button>
    <el-button @click="changeRankInfo({matchApplyNumber:'MATCH000274-000003',num:2,time:'12:30',taskName:'nihao'})" style="position: absolute;z-index:999;left:50px" type="warining" size="normal">click</el-button>
    <el-button @click="changeRankInfo({matchApplyNumber:'MATCH000274-000001',num:3,time:'12:30',taskName:'nihao'})" style="position: absolute;z-index:999;left:100px" type="warining" size="normal">click</el-button> -->
    <div class="my-echarts">
      <!-- 头部标题 -->
      <div class="charts-title">
        <div class="charts-title-txt">{{InfoObj.courseName}}</div>
      </div>
      <!-- 左侧rank排名 -->
      <div class="left-rank">
        <div class="left-rank-title title-txt"><span>竞赛排名</span></div>
        <div class="left-rank-main">
          <div class="table rank-table">
            <div class="thead">
              <div class="tr">
                <div class="th" style="width:18%;"><i class="el-icon-s-custom"></i>&nbsp; 团队</div>
                <div class="th" style="width:30%;"><i class="el-icon-user"></i>&nbsp;成员</div>
                <div class="th" style="width:30%;"><i class="el-icon-data-line"></i>&nbsp;进度</div>
                <div class="th" style="width:20%;"><i class="el-icon-time"></i>&nbsp;任务提交时间</div>
              </div>
            </div>
            <div class="tbody" v-if="list.length>0">
              <div class="tr" v-for="(item,index) in list" :key="`a${index}`" :style="`top:${10*index}%`" ref="item">
                <!-- 团队名 -->
                <div class="td teamName" :style="item.teamName.length>10?'font-size:50%;text-align:start;line-height:1.2;':''">
                  {{item.teamName==undefined||item.teamName=='' ?'-':item.teamName}}
                </div>
                <!-- 团队成员 -->
                <div class="td userNames" :style="item.userNames.length>=5?item.userNames.length>=7?'font-size:50%;line-height:1.2;text-align:start;' : 'font-size:50%;line-height:1.2;' : ''">
                  <span v-for="(items,index) in item.userNames" :key="index">{{items}}</span>
                </div>
                <!-- 完成进度 -->
                <div class="td submitReportNum">
                  <div class="inner-item" v-show="!isChange">
                    <el-progress :stroke-width="26" :percentage="baifen(item.submitReportNum, InfoObj.taskNum)" :show-text="false"></el-progress>
                    <span>{{ item.submitReportNum }}/{{ InfoObj.taskNum}}</span>
                  </div>
                  <div class="inner-item2" v-show="isChange"> 完成任务{{taskNum}}：{{changeName}} </div>

                </div>
                <!-- 提交时间 -->
                <div class="td time">{{item.time||'-'}}</div>
              </div>
              <!-- <div class="tr changeTr" :style="`top:50%`" ref="item2">
                <div class="td teamName"> 超级飞侠xxxxxxxxxxxxxxxxxxxxxxxx </div>
                <div class="td userNames"> 太极张三丰xxxxxxxxxxxxxxxxxxxx </div>
                <div class="td submitReportNum"> 完成任务1：xxxxxxxxxxxxxxxxxxxxxx </div>
                <div class="td time"> 12:00xxxxxxxxxxxxxxxxxxxxxxxxxxxxx </div>
              </div> -->
            </div>
            <div class="tbody" v-else>
              <div class="tr">
                <div class="td">暂无数据</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右上统计饼图 -->
      <div class="right-pie">
        <div class="right-pie-title title-txt"><span>已完成队伍</span></div>
        <div class="right-pie-main">
          <!-- echarts -->
          <div class="echarts" id="statistic_echarts"></div>
          <!-- 文字部分 -->
          <div class="rank-content-txt">
            <div class="finish-txt">
              <span class="one">已完成</span>
              <span class="two">{{InfoObj.finishedTeamNum}}</span><span class="three">队</span>
            </div>
            <div class="unfinish-txt">
              <span class="one">未完成</span>
              <span class="two">{{InfoObj.unFinishedTeamNum}}</span><span class="three">队</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 右下柱状图 -->
      <div class="right-histogram">
        <div class="right-histogram-title title-txt">
          <span>任务完成情况</span>
        </div>
        <div class="right-histogram-out">
          <div class="right-histogram-main" id="statistic_echarts2"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  RealTimeRanking,
  getLiveWebsocketTSCP,
} from '@/api/competitionPlatform'

export default {
  name: 'CompetitionLive',
  data() {
    return {
      //课程id
      courseId: 0,
      // 第一次请求拿到的数据整体   groupType组织类型
      InfoObj: {},
      //记录定时器
      Interval1: '',
      // 组织形式  2团队，1个人
      groupType: 0,

      // 用于渲染部分--------------------------------start
      //左侧排名列表
      list: [],
      //右下柱状图--任务名
      taskName: [],
      //右下柱状图--排名
      histogramData: [],
      //发生改变时提交的任务名称
      changeName: '',
      // 用于渲染部分----------------------------------end

      //数据更新--------------------------------start
      //是否有数据更新
      isChange: false,
      // 完成的是第几份报告
      taskNum: 0,
      // 排行榜数据变化，dom节点不会跟着变化。这个变量记录数据list数据列表最后一个元素对应的dom节点
      trPositioning: 10,
      //数据更新----------------------------------end
    }
  },
  created() {
    this.courseId = this.$localstorage.getLocalStorage('setCourseId')
    //获取排名数据
    this.getRanking()
    // websock
    this.InitWebSocket()
  },
  mounted() {
    this.Interval1 = setInterval(() => {
      this.getEcharts()
    }, 1000)
  },
  destroyed() {
    clearInterval(this.Interval1)
  },
  computed: {
    //右上角饼图完成百分比计算
    submissionsPercentage() {
      if (
        this.InfoObj.finishedTeamNum == 0 ||
        this.InfoObj.unFinishedTeamNum == 0
      ) {
        return 0
      }
      return parseInt(
        (this.InfoObj.finishedTeamNum /
          (this.InfoObj.finishedTeamNum + this.InfoObj.unFinishedTeamNum)) *
          100
      )
    },
  },
  methods: {
    //获取排名信息
    getRanking() {
      RealTimeRanking(this.courseId).then((res) => {
        if ((res.code = 200)) {
          this.InfoObj = res.data
          //组织形式
          this.groupType = res.data.groupType
          //左侧排名数据列表设置--start
          this.list = JSON.parse(JSON.stringify(this.InfoObj.schedule))
          //根据提交任务数量排序
          // this.list.sort(this.sortProMax('submitReportNum'))
          // 取11条数据
          this.list.splice(11)
          //左侧排名数据列表设置--end

          // 设置右下角柱状图数据
          this.makeRankInfo()
        }
      })
    },
    // 右下柱状图排名信息处理
    makeRankInfo() {
      // 1.根据完成任务队伍数量排序
      let taskRank = JSON.parse(JSON.stringify(this.InfoObj.task))
      taskRank.sort(this.sortProMax('finishedTeamNum'))
      this.histogramData = []
      this.taskName = []
      //2.最多拿5条数据,不够补空字符
      for (let i = 0; i < 5; i++) {
        if (i < taskRank.length) {
          this.histogramData.push(taskRank[i].finishedTeamNum)
          this.taskName.push('任务' + taskRank[i].num)
        } else {
          // this.histogramData.push('')
          // this.taskName.push('')
        }
      }
    },
    //更改排名时的数据处理设置
    changeRankInfo(task) {
      //左侧排名表设置---------------------------------------------------------start
      let changeObj = {} //需要改变的数据到时候会存在这里面
      let changeIndex = 0 //需要改变的数据，在this.list里的的索引号
      this.InfoObj.schedule.forEach((item, index) => {
        if (item.matchApplyNumber == task.matchApplyNumber) {
          item.submitReportNum += 1
          //提交的是第几份报告
          item.submitChapterNum = task.num
          // 提交时间
          item.time = task.time
          //赋值给changeObj
          changeObj = item
          //要更改的数据在11个以内时
          if (index <= 10) {
            //确定要改变的元素在list里面的位置
            let listIndex
            this.list.forEach((item, index) => {
              if (item.matchApplyNumber == task.matchApplyNumber) {
                listIndex = index
              }
            })
            //更新用于渲染的list
            this.list.splice(listIndex, 1, changeObj)
            // 更新元素在InfoObj的位置
            this.InfoObj.schedule.splice(index, 1, changeObj)
            changeIndex = listIndex
          } else {
            //在11个以外时
            this.list.splice(this.trPositioning, 1, changeObj)
            // 更新元素在InfoObj的位置
            this.InfoObj.schedule.splice(index, 1)
            // 把它放在第1位
            this.InfoObj.schedule.splice(0, 0, changeObj)

            changeIndex = this.trPositioning
            // 11个一轮，更新trPositioning
            if (this.trPositioning >= 1) {
              this.trPositioning -= 1
            } else {
              this.trPositioning = 10
            }
          }
          // 右上角饼图数据设置
          //一个队伍提交完所有任务报告，才视为完成当前竞赛，已完成队伍数量才会+1
          if (item.submitReportNum == this.InfoObj.taskNum) {
            //已完成队伍+1
            this.InfoObj.finishedTeamNum += 1
            //未完成队伍-1
            this.InfoObj.unFinishedTeamNum -= 1
          }
        }
      })
      //左侧排名更新，整行上移动画
      // 排行榜所有行dom节点
      let doms = this.$refs.item
      // 要发生改的那一行数据的节点
      let changeTop = doms[changeIndex].style.top.replace('%', '')
      // 操作要改变的dom节点
      doms[changeIndex].className = 'tr changeTr'
      this.changeName = task.taskName
      this.isChange = true
      this.taskNum = task.num
      doms[changeIndex].style.zIndex = 999
      // 下移动画
      for (let i = 0; i < doms.length; i++) {
        let top = doms[i].style.top.replace('%', '')
        //改变节点以上 行 全部下移
        if (parseInt(top) <= parseInt(changeTop)) {
          doms[i].style.top = 10 + parseInt(top) + '%'
        }
      }
      // aaaaaaaaaa
      doms[changeIndex].style.top = 0 + '%'
      setTimeout(() => {
        doms[changeIndex].className = 'tr'
        this.isChange = false
      }, 1000)
      // 左侧排名表设置---------------------------------------------------------end

      // 对右下角柱状图数据做处理---------------------------------------------------------start
      this.InfoObj.task.forEach((item, index) => {
        if (item.num == task.num) {
          // 完成任务数量+1
          item.finishedTeamNum += 1
        }
      })
      // 调用更新柱状图数据函数
      this.makeRankInfo()
      // 对右下角柱状图数据做处理---------------------------------------------------------end
    },
    // websock开始
    InitWebSocket() {
      let hostname = window.location.host
      const wsuri = 'ws://' + hostname + '/tes/ws/global'
      this.websock = new WebSocket(wsuri)
      this.websock.onopen = this.websocketonopen
      this.websock.onmessage = this.websocketonmessage
      this.over = () => {
        this.websock.close()
      }
    },
    websocketonopen() {
      console.log('open sucess')
    },
    websocketonmessage(e) {
      //数据接收
      let res = JSON.parse(e.data)
      if (res.type == 32) {
        this.changeRankInfo(res.task)
      }
    },
    //webscokt结束

    //对象数组排序----大到小
    sortProMax(attribute) {
      return function (a, b) {
        return b[attribute] - a[attribute]
      }
    },
    //左侧表格完成进度百分比转换
    baifen(a, b) {
      if (b == 0) {
        return 0
      }
      return parseInt((a * 100) / b)
    },
    // echart图
    getEcharts() {
      let that = this
      var chartDom = document.getElementById('statistic_echarts')
      var myChart = echarts.init(chartDom)
      var option
      var chartDom2 = document.getElementById('statistic_echarts2')
      var myChart2 = echarts.init(chartDom2)
      var option2
      //仪表图
      option = {
        grid: {
          x: 10,
          y: 10,
          x2: 10,
          y2: 10,
        },
        series: [
          {
            type: 'gauge',
            center: ['50%', '60%'],
            startAngle: 200,
            endAngle: -20,
            min: 0,
            max: 100,
            splitNumber: 12,
            itemStyle: {
              color: '#02a1ff',
            },
            progress: {
              show: true,
              width: 20,
            },
            axisLine: {
              lineStyle: {
                width: 20,
                color: [[1, '#2c2dac']],
              },
            },

            pointer: {
              show: false,
            },

            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            anchor: {
              show: false,
            },
            title: {
              offsetCenter: [0, '20%'],
              fontSize: 15,
              color: '#02a1ff',
            },
            detail: {
              valueAnimation: true,
              width: '60%',
              lineHeight: 40,
              borderRadius: 8,
              offsetCenter: [0, '-5%'],
              fontSize: 25,
              fontWeight: 'bolder',
              formatter: '{value} %',
              color: 'auto',
            },
            data: [
              {
                value: that.submissionsPercentage,
                name: '已完成占比',
              },
            ],
          },
        ],
      }
      // 柱状图
      option2 = {
        grid: {
          x: 50,
          y: 10,
          x2: 50,
          y2: 10,
        },
        xAxis: {
          show: false,
        },
        yAxis: {
          type: 'category',
          inverse: true,
          data: that.taskName,
          axisLabel: {
            show: true,
            textStyle: {
              color: '#ddd',
            },
          },
        },
        series: [
          {
            name: 'City Beta',
            realtimeSort: true,
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  var colorList = [
                    '#1E90FF',
                    '#6495ED',
                    '#4682B4',
                    '#02a1ff',
                    '#2c2dac',
                  ]
                  return colorList[params.dataIndex]
                },
                label: {
                  show: true,
                  position: 'right',
                  color: '#FFF',
                  fontWeight: 100,
                  formatter: function (params) {
                    return params.value + '/' + that.InfoObj.joinNum
                  },
                },
              },
            },
            label: {
              show: true,
              position: 'right',
              valueAnimation: true,
            },
            data: that.histogramData,
          },
        ],
      }
      option && myChart.setOption(option)
      option2 && myChart2.setOption(option2)
      window.addEventListener('resize', function () {
        myChart.resize()
        myChart2.resize()
      })
    },
  },
}
</script>
<style lang="scss">
#CompetitionLive {
  .el-progress {
    width: 80%;
  }
  .list-enter-active {
    transition: all 1s ease;
  }

  .list-enter-from,
  .list-leave-to {
    opacity: 0;
  }

  .list-move {
    transition: transform 1s ease;
  }
  .list-leave-active {
    position: absolute;
    transition: all 1s ease;
  }
}
</style>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
#CompetitionLive {
  width: 100vw;
  height: 100vh;
  .my-echarts {
    width: 100%;
    height: 100%;
    min-width: 1280px;
    min-height: 800px;
    background-image: url(../../../assets/images/liveBackground.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    position: relative;
    //标题
    .charts-title {
      width: 100%;
      height: 10.9%;
      position: relative;
      .charts-title-txt {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 200%;
        font-weight: 900;
        color: #fff;
      }
    }
  }
  // 标题文字
  .title-txt {
    background-image: url(../../../assets/images/liveTitle.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    position: absolute;
    display: flex;
    align-items: center;
    font-size: 500;
    color: #fff;
  }
  // 左侧排名表
  .left-rank {
    width: 61.2%;
    height: 75.6%;
    min-width: none;
    min-height: none;
    position: absolute;
    top: 15.2%;
    left: 3.4%;
    .left-rank-title {
      width: 19.9%;
      height: 6.9%;
      font-size: 120%;
      top: 1%;
      left: 4%;
      span {
        margin-left: 35%;
      }
    }

    .left-rank-main {
      width: 90%;
      height: 92%;
      position: absolute;
      top: 7.9%;
      left: 50%;
      transform: translateX(-50%);
      .inner-item {
        display: flex;
        justify-content: space-between;
      }
      .inner-item2 {
        width: 100%;
        padding: 0 10px 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .rank-table {
        width: 100%;
        height: 90%;
        color: #fff;
        font-weight: 500;
        font-size: 120%;
        // overflow: hidden;
        // overflow-y: hidden;
        .tr,
        .td {
          background-color: transparent;
          text-align: center;
        }
        .tr {
          border-bottom: 2px solid #0552a4;
        }
        .thead {
          height: 9%;
          .tr {
            height: 100%;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;

            box-sizing: border-box;
            .th:nth-child(1) {
              width: 20%;
            }
            .th:nth-child(2) {
              width: 30%;
            }
            .th:nth-child(3) {
              width: 30%;
            }
            .th:nth-child(4) {
              width: 20%;
            }
          }
        }
        .tbody {
          position: relative;
          height: 91%;
          width: 100%;
          .tr {
            height: 10%;
            width: 100%;
            position: absolute;
            display: flex;
            align-items: center;
            transition: 1s;
            justify-content: center;
            box-sizing: border-box;
          }
          .teamName {
            width: 18%;
          }
          //团队成员名字样式--start
          .userNames-personal {
            width: 30%;
            text-align: center;
          }
          .userNames {
            width: 30%;
            padding: 0 10px 0 10px;
            // display: flex;
            // flex-flow: row wrap;
            // justify-content: center;
            text-align: center;
            span {
              margin-right: 2%;
            }
          }
          //团队成员名字样式--end
          .submitReportNum {
            width: 30%;
          }
          .time {
            width: 20%;
          }
          .changeTr {
            width: 105%;
            height: 15%;
            font-size: 150%;
            z-index: 999;
            margin: -5px 0 0 -18px;
            box-sizing: border-box;
            padding: 0 2.5% 0 2.5%;
            background-image: url(../../../assets/images/livingChangeTr.png);
            background-size: 100% 100%;
            background-repeat: no-repeat;
            color: yellow;
            border: none;
            display: flex;
            justify-content: center;
            .td {
              padding: 0 10px 0 10px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .td:nth-child(1) {
              width: 20%;
            }
            .td:nth-child(2) {
              width: 30%;
            }
            .td:nth-child(3) {
              width: 30%;
            }
            .td:nth-child(4) {
              width: 20%;
            }
          }
        }
      }
    }
  }
  // 右侧统计饼图
  .right-pie {
    width: 30.2%;
    height: 35.2%;
    position: absolute;
    top: 15.2%;
    right: 3.4%;
    .right-pie-title {
      width: 50%;
      height: 15%;
      top: 1%;
      left: 4%;
      font-size: 120%;
      span {
        margin-left: 33%;
      }
    }

    .right-pie-main {
      width: 100%;
      height: 85%;
      position: absolute;
      top: 16%;
      right: 0%;
      display: flex;
      align-items: center;
      justify-content: center;
      .echarts {
        width: 45%;
        height: 100%;
      }
      .rank-content-txt {
        width: 45%;
        height: 40%;
        border: 2px solid #0552a4;
        // box-shadow:10px 10px  10px #051a75;
        box-sizing: border-box;
        // 051a75 037eff
        display: flex;
        .finish-txt,
        .unfinish-txt {
          display: flex;
          justify-content: center;
          align-content: space-around;
          align-items: baseline;
          flex-flow: row wrap;
          width: 50%;
          height: 100%;
          .one,
          .three {
            font-size: 150%;
            font-weight: 500;
          }
          .one {
            width: 100%;
            text-align: center;
          }
          .two {
            font-size: 200%;
            font-weight: 500;
          }
        }
        .finish-txt {
          color: #02ed8e;
          border-right: 2px solid #0552a4;
        }
        .unfinish-txt {
          color: #efde14;
        }
      }
    }
  }
  // 右侧柱状图
  .right-histogram {
    width: 30.2%;
    height: 37.8%;
    position: absolute;
    bottom: 9.6%;
    right: 3.4%;
    .right-histogram-title {
      width: 50%;
      height: 15%;
      top: 1%;
      left: 4%;
      font-size: 120%;
      span {
        margin-left: 35%;
      }
    }
    .right-histogram-out {
      width: 100%;
      height: 75%;
      display: flex;
      align-items: center;
      position: absolute;
      top: 16%;
      right: 0%;
      .right-histogram-main {
        margin-top: 40px;
        width: 100%;
        height: 75%;
      }
    }
  }
}
</style>